package ch.zbw.sysventory.server.scanner;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import org.apache.log4j.Logger;

public class ConnectionTester {

	private Logger logger = Logger.getRootLogger();

	public boolean testConnection(String ipAddress, int port) {
		Socket socket = new Socket();
		SocketAddress socketAddress = new InetSocketAddress(ipAddress, port);
		try {
			socket.connect(socketAddress, 3000);
			if (socket.isConnected()) {
				String messageSend = "TestMessage";
				byte[] sendMessageBytes = messageSend.getBytes();
				OutputStream out = socket.getOutputStream();
				DataOutputStream dos = new DataOutputStream(out);
				dos.writeLong(sendMessageBytes.length);
				dos.write(sendMessageBytes, 0, sendMessageBytes.length);
				dos.flush();
				return true;
			}
			socket.close();
		} catch (IOException e) {
			logger.info(e.getMessage());
		}
		return false;
	}

}
